<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace front\modules\web\controllers;


use coupons\services\CouponsGroupService;
use EasyWeChat\Support\XML;
use order\models\Orders;
use order\services\OrderService;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Controller;

use EasyWeChat\Foundation\Application;

class PayController extends Controller
{

    private $_appId = '';
    private $_appSecret = '';
    private $_mch_id = '';
    private $_mch_key = '';

    public function init()
    {
        \Yii::$app->request->enableCsrfValidation = false;
    }


    public function actionNotify_3()
    {
        Yii::info("***************XML*******************");

        $xmlInput = file_get_contents('php://input');
        $input = XML::parse($xmlInput);
        Yii::info($input);
        $_appId = $input['appid'];//ios : wx0417aa0c4668fb0c  //wechat : wxb92c2bb9c487c950
        $_mch_id = $input['mch_id'];
        $_mch_key = 'Yk3Bn8sBsg2yJ83gfkKHgfehe7Hdggsk';
        $options = [
            'app_id' => $_appId,
            'payment' => [
                'merchant_id'        => $_mch_id,
                'key'                => $_mch_key,
            ],
        ];

        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Orders::findOne(['order_id' => $notify->out_trade_no]);
            $order = ArrayHelper::toArray($order);
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            // 检查订单是否已经更新过支付状态
            if ($order['status'] > 0) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 微信支付成功，改我们的状态
            if ($successful) {
                $data = [];
                array_push($data,[
                    'order_id' => $notify->out_trade_no,
                    'cost' => $notify->cash_fee / 100,
                    'payment_type' => 1,
                ]);
                $result = OrderService::payOrder($data);
                \Yii::info($result, "***************支付成功*******************");
                if ($result['code'] != 0) {
                    return '暂时无法更新订单状态~';
                }
                if (isset($order['use_coupons']) && !empty($order['use_coupons'])) {
                    $use_coupons = $order['use_coupons'];
                    //存入卡券流水
                    foreach ($use_coupons as $k => $v) {
                        $couponsRes = CouponsGroupService::pay($order['customer_id'], $v['coupons_id'], $order['order_id'], $v['coupons']);
                        \Yii::info($couponsRes, "****************卡券流水******************");
                    }
                }
            }

            return true; // 或者错误消息
        });

        echo $response->send();//return $response;// 或者 $response->send()
    }
}